﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Wombat.Client.Core
{
    internal class ClientConfigurationLoader : IClientConfigurationLoader, IConfigurationService
    {
        internal static class Keys
        {
            public static readonly string WebServices = "DataSubmissionWebservice";
            public static readonly string BaseAddresss = "baseaddress";
            public static readonly string Binding = "binding";
        }
        private const string Delimiter = "___~~~___```";

        private Dictionary<string, string> _configs = new Dictionary<string, string>();

        private XName N(string name)
        {
            return XName.Get(name);
        }

        public void LoadConfiguration(XDocument doc)
        {
            var configElem =
                doc.Elements().Where(e => e.Name.LocalName.Equals("configuration", StringComparison.OrdinalIgnoreCase));
            if (configElem == null)
                throw new FormatException("Bad configuration format. Tag 'configuration' does not exist.");
            _configs = configElem.Elements().SelectMany(e =>
                                                        e.Elements()
                                                         .Select(
                                                             se =>
                                                             new
                                                                 {
                                                                     Section = Section(e.Name.LocalName, se.Name.LocalName),
                                                                     Value = GetValue(se)
                                                                 }))
                                 .ToDictionary(kvp => kvp.Section, kvp => kvp.Value);
        }

        private static string Section(string section, string name)
        {
            return string.Format("{0}{1}{2}", section.ToLowerInvariant(), Delimiter, name.ToLowerInvariant());
        }

        private static string GetValue(XElement se)
        {
            var att = se.Attribute("value");
            if (att != null)
                return (string)se.Attribute("value");
            return se.Value;
        }

        public string GetConfigurationValue(string section, string key)
        {
            var dicKey = Section(section, key);
            if (_configs.ContainsKey(dicKey))
                return _configs[dicKey];
            return null;
        }
    }
}